package com.example.supermarket_back.service.Impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.supermarket_back.config.cache.CacheConfig;
import com.example.supermarket_back.dao.LoginDao;
import com.example.supermarket_back.service.LoginService;
import com.example.supermarket_back.utils.CommonUtil;
import com.example.supermarket_back.utils.JWTUtils;
import com.example.supermarket_back.utils.constants.ErrorEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginImpl implements LoginService {

    @Resource
    private LoginDao loginDao;

    @Resource
    private CacheConfig cacheConfig;

    @Override
    public JSONObject verifyUserAccount(String username, String password) {
        Map<String, String> map = new HashMap<>();
        map.put("user", username);
        map.put("uuid", IdUtil.simpleUUID());
        int res=0;
        try {
            res = loginDao.verifyAccount(Integer.parseInt(username),password);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        if (res==1) {
            String token= JWTUtils.getToken(map);
            cacheConfig.addToRedis(token, username);
            return CommonUtil.successJson(token);
        }else {
            return CommonUtil.errorJson(ErrorEnum.E_407);
        }
    }

    @Override
    public JSONObject verifyUserEmail(String email,String password) {
        Map<String, String> map = new HashMap<>();
        map.put("user", email);
        map.put("uuid", IdUtil.simpleUUID());
        int res=loginDao.verifyEmail(email,password);
        if (res==1) {
            String token= JWTUtils.getToken(map);
            cacheConfig.addToRedis(token, email);
            return CommonUtil.successJson(token);
        }else {
            return CommonUtil.errorJson(ErrorEnum.E_407);
        }
    }

    @Override
    public JSONObject updatePassWord(String email, String password,String captcha) {
        boolean equal= Objects.equals(captcha, cacheConfig.getData(email));
        boolean success=false;
        if(equal){
            success=loginDao.updatePassWord(email,password)==1;
            cacheConfig.deleteKey(email);
        }
        return success?CommonUtil.successJson():CommonUtil.errorJson(ErrorEnum.E_410);
    }

    @Override
    public boolean loginOut(String token) {
        return cacheConfig.deleteKey(token);
    }
}
